package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.constant.MessageConstant;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Resource
    private IUserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private IFollowService followService;

    /**
     * 定义查询的页数
     */
    private static final Long SCROLL_PAGE = 2L;


    @Override
    public Result queryHostBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog -> {
            this.queryUser(blog);
            this.queryIsLike(blog);
        });
        return Result.success(records);
    }

    /**
     * 查询单条探店笔记
     * @param id
     * @return
     */
    @Override
    public Result queryBlogById(Long id) {
        // 查询笔记信息
        Blog blog = getById(id);
        if(blog == null){
            return Result.error(MessageConstant.BLOG_IS_NOT_EXISTS);
        }
        // 查询笔记是否被当前登录用户点赞
        queryIsLike(blog);

        // 查询发布笔记的用户信息
        queryUser(blog);
        return Result.success(blog);
    }

    /**
     * 修改点赞功能
     * @param id
     * @return
     */
    @Override
    public Result updateIsLike(Long id) {
        // 1.查询该笔记信息
        Blog blog = getById(id);
        // 1.1获取用户信息和key
        Long userId = UserHolder.getUser().getId();
        String key = RedisConstants.BLOG_LIKED_KEY + id;
        // 2.判断该笔记是否被点赞
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        if(score == null){
            // 3.没被点赞则可以点赞
            // 3.1修改isLike属性
            boolean result = update().setSql("liked = liked + 1").eq("id", id).update();
            // 3.2将该用户信息写进redis的set集合中 SADD key userId
            if(result){
                stringRedisTemplate.opsForZSet().add(key, userId.toString(), System.currentTimeMillis());
            }
        }else{
            // 4.被点赞了就取消点赞
            // 4.1修改isLike属性
            boolean result = update().setSql("liked = liked - 1").eq("id", id).update();
            // 4.2将用户信息从set集合中删除
            if(result){
                stringRedisTemplate.opsForZSet().remove(key, userId.toString());
            }
        }
        return Result.success();
    }

    /**
     * 查询笔记点赞排行前五
     * @param id
     * @return
     */
    @Override
    public Result queryBlogLikesTop5(Long id) {
        // 1.从redis里查询为该条笔记点赞的userId
        String key = RedisConstants.BLOG_LIKED_KEY + id;
        Set<String> top5 = stringRedisTemplate.opsForZSet().range(key, 0, 4);

        // 2.解析userId并封装成userList对象
        if(top5 == null || top5.isEmpty()){
            return Result.success(Collections.emptyList());
        }
        // 转化成Long类型的id集合 WHERE id IN(5, 1) ORDER BY field(id, 5, 1)
        // in()会将排行顺序进行倒序，得用field指令自定义排序规则
        List<Long> ids = top5.stream().map(Long::valueOf).collect(Collectors.toList());
        // 进行二次校验
        if(ids.isEmpty()){
            return Result.success(Collections.emptyList());
        }
        String idsStr = StrUtil.join(",", ids);
        List<UserDTO> userDTOList = userService.query()
                .in("id", ids).last("ORDER BY FIELD(id,"+ idsStr + ")").list()
                .stream().map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        // 3.返回userList
        return Result.success(userDTOList);
    }

    /**
     * 发布探店笔记
     * @param blog
     * @return
     */
    @Override
    public Result saveBlog(Blog blog) {
        // 1.获取当前登陆的用户
        UserDTO userDTO = UserHolder.getUser();
        if(userDTO == null){
            return Result.error(MessageConstant.USER_IS_UNLOAD);
        }
        Long userId = userDTO.getId();
        blog.setUserId(userId);
        // 2.保存blog笔记到数据库
        boolean isSuccess = save(blog);
        if(!isSuccess){
            return Result.error(MessageConstant.BLOG_LOAD_FAILED);
        }
        // 3.向粉丝推送当前发送的笔记
        // 3.1获取当前登陆用户的粉丝集合
        List<Follow> followList = followService.query().eq("follow_user_id", userId).list();
        if(followList.isEmpty()){
            return Result.success(blog.getId());
        }
        // 3.2将笔记推送给粉丝
        for (Follow follow : followList) {
            // 获取粉丝id
            Long fansId = follow.getUserId();
            String key = RedisConstants.FEED_KEY + fansId;
            // 将blog推送到粉丝的收件箱里
            stringRedisTemplate.opsForZSet().add(key, blog.getId().toString(), System.currentTimeMillis());
        }
        // 4.返回
        return Result.success(blog.getId());
    }


    /**
     * 滚动查询推送的blog
     * @param maxTime 上次查询的最小时间戳 - 这次查询的最大时间戳
     * @param minTimeCount 和上次查询最小时间戳相等的个数 - 偏移量
     * @return
     */
    @Override
    public Result queryBlogOfFollows(Long maxTime, Long minTimeCount) {
        // 1.获取当前登陆用户
        UserDTO user = UserHolder.getUser();
        if(user == null){
            return Result.error(MessageConstant.USER_IS_UNLOAD);
        }
        Long userId = user.getId();
        // 2.获取当前用户的收件箱 ZREVRANGEBYSCORE key MAX MIN WITHSCORES 3 --OFFSET 2 --COUNT
        String key = RedisConstants.FEED_KEY + userId;
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet().reverseRangeByScoreWithScores(
                key, 0, maxTime, minTimeCount, SCROLL_PAGE
        );
        // 2.1判断typeTuples是否为空
        if(typedTuples == null || typedTuples.isEmpty()){
            return Result.success();
        }
        // 3.解析数据 blogId, minTime, offsetCount
        // 创建blogIds集合
        List<Long> ids = new ArrayList<>(typedTuples.size());
        Long minTime = 0L;
        Integer offsetCount = 1;
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
            // 3.1获取blogId
            ids.add(Long.valueOf(typedTuple.getValue()));
            // 3.2获取minTime
            long time = typedTuple.getScore().longValue();
            if(time == minTime){
                // 如果当前时间戳等于最小时间戳，偏移量计数加一
                offsetCount++;
            }else{
                // 不等于就将time赋值给最小时间戳，偏移量初始化
                minTime = time;
                offsetCount = 1;
            }
        }
        // 4.根据id查询blog集合
        String idsStr = StrUtil.join(",", ids);
        List<Blog> blogList = query().in("id", ids)
                .last("ORDER BY FIELD(id," + idsStr + ")")
                .list();
        for (Blog blog : blogList) {
            // 查询用户信息
            queryUser(blog);
            // 查询点赞信息
            queryIsLike(blog);
        }

        // 5.封装ScrollResult数据并返回
        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setList(blogList);
        scrollResult.setMinTime(minTime);
        scrollResult.setOffset(offsetCount);

        return Result.success(scrollResult);
    }

    /**
     * 查询用户信息
     * @param blog
     */
    private void queryUser(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }

    /**
     * 判断笔记是否被当前登陆用户点赞
     * @param blog
     */
    private void queryIsLike(Blog blog) {
        // 1.1获取用户信息和key
        UserDTO user = UserHolder.getUser();
        if(user == null){
            blog.setIsLike(false);
            return;
        }
        Long userId = user.getId();
        String key = RedisConstants.BLOG_LIKED_KEY + blog.getId();
        // 2.判断该笔记是否被点赞
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        blog.setIsLike(Objects.nonNull(score));
    }

}
